from odoo import fields, models, api
from odoo.exceptions import UserError

ADJUST_FOR = [('all_mail_route', '所有邮路'), ('single_mail_route', '单一邮路'), ('all_value_add', '所有增值(二级)'), ('single_value_add', '单一增值')]


class RPShipperSalePriceAdjustment(models.Model):
    _name = "rp.shipper.sale.price.adjustment"
    _description = '托运商销售调价'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _sql_constraints = [('unique_name', 'UNIQUE(code)', '编号必须唯一')]
    _rec_name = 'name'

    name = fields.Char(string='名称', required=True)
    code = fields.Char(string='编码', default='RP_SSP/*****', index=True, readonly=True)

    shipper_sale_template_id = fields.Many2one(string='销售价模板', comodel_name='rp.shipper.sale.template', required=True, tracking=True)
    shipper_id = fields.Many2one(string='托运商', comodel_name='rp.shipper', related='shipper_sale_template_id.shipper_id', store=True, tracking=True)
    adjust_for = fields.Selection(string='调价对象', selection=ADJUST_FOR, default=ADJUST_FOR[1][0], tracking=True)
    """ 
    为了计算价格的时候迅速核算调价，采取的策略并不是在调价中查询满足条件的记录，而是通过在销售价模板中通过o2m关联锁定
    这样的好处是避免了算价格时多一次庞大的查询
    """
    shipper_sale_template_mail_route_id = fields.Many2one(string='销售邮路', comodel_name='rp.shipper.sale.template.mail.route.line', tracking=True)
    shipper_sale_template_value_added_id = fields.Many2one(string='销售增值服务', comodel_name='rp.shipper.sale.template.value.added.line', tracking=True)

    price_adjust_rule_id = fields.Many2one(string='调价规则', comodel_name='rp.price.adjust.rule', required=True)

    active_flag = fields.Boolean(string='有效', related='shipper_sale_template_id.active_flag', store=True)
    remarks = fields.Text(string='备注')

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['code'] = self.env['ir.sequence'].sudo().next_by_code('rp.shipper.sale.price.adjustment') or '/'
        result = super(RPShipperSalePriceAdjustment, self).create(vals_list)
        return result

    @api.onchange('adjust_for')
    def _onchange_adjust_for(self):
        if self.adjust_for == ADJUST_FOR[0][0]:
            self.update({'shipper_sale_template_mail_route_id': False,
                         'shipper_sale_template_value_added_id': False,
                         'price_adjust_rule_id': False})
        elif self.adjust_for == ADJUST_FOR[1][0]:
            self.update({'shipper_sale_template_value_added_id': False,
                         'price_adjust_rule_id': False})
        elif self.adjust_for == ADJUST_FOR[2][0]:
            self.update({'shipper_sale_template_mail_route_id': False,
                         'shipper_sale_template_value_added_id': False,
                         'price_adjust_rule_id': False})
        elif self.adjust_for == ADJUST_FOR[3][0]:
            self.update({'shipper_sale_template_mail_route_id': False,
                         'price_adjust_rule_id': False})
